package commands

import (
	"errors"

	"github.com/larspensjo/config"
	"github.com/urfave/cli"

	"../flags"
	"../utils"
)

// Login - login user
func Login(config utils.Config) cli.Command {
	return cli.Command{
		Name:     "login",
		Usage:    "login",
		Category: "USER COMMANDS",
		Flags: []cli.Flag{
			flags.Flags["path"],
			cli.StringFlag{
				Name:  "name",
				Usage: "login with `NAME`",
			},
		},
		Action: makeAction(config, loginAction),
	}
}

func loginAction(conf utils.Config, git utils.Git, context *cli.Context) error {
	result, err := utils.LoadConfig(conf, git, "config")
	if err != nil {
		return err
	}

	var name = context.String("name")
	_, err = result.String("user", name)
	if err != nil {
		return errors.New("User doesn't exist")
	}

	return utils.AddConfig(conf, git, "config", func(c *config.Config) *config.Config {
		c.AddOption("session", conf.PcCode, name)
		return c
	})
}
